package abcy.cloud.authenticationserver.controller;


import abcy.cloud.authenticationserver.dto.req.SysLoginUserReq;
import abcy.cloud.authenticationserver.dto.resp.LoginUserInfoResp;
import abcy.cloud.authenticationserver.dto.resp.LoginUserResp;
import abcy.cloud.authenticationserver.services.LoginService;
import abcy.cloud.blogcommon.resp.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;

    @RequestMapping(value = "/doLogin")
    @ResponseBody
    public ResponseEntity login(@RequestBody(required = false) SysLoginUserReq sysLoginUserReq, HttpServletRequest req) {
        String ipAddress = req.getRemoteAddr();
        System.out.print(ipAddress);
        sysLoginUserReq.setLoginIp(ipAddress);
        Map<Object, Object> resultMap = loginService.doLogin(sysLoginUserReq, req);
        if(Objects.equals(1, resultMap.get("code"))) {
            return ResponseEntity.fail();
        }
        Object token = resultMap.get("access_token");
        /*if(Objects.nonNull(token)) {
            response.setHeader("Authorization", token.toString());
            response.setHeader("Access-Control-Expose-Headers", "Authorization");
        }
        log.info(response.getHeader("Authorization"));
        log.info(str);*/
        LoginUserInfoResp loginInfoResp = new LoginUserInfoResp();
        loginInfoResp.setAccessToken(resultMap.get("access_token").toString());
        loginInfoResp.setUsername(resultMap.get("username").toString());
        loginInfoResp.setUserId(resultMap.get("userId").toString());
        loginInfoResp.setLoginUserResp((LoginUserResp) resultMap.get("loginUserResp"));
        /*Object roles = resultMap.get("authOrity");
        Set<String> rolesstr = new HashSet<>();
        for(Object role: (List<String>)roles){
            rolesstr.add(String.class.cast(role));
        }
        loginInfoResp.setRoles(rolesstr);
        Object permissions = resultMap.get("userPermission");
        Set<String> permissionsstr = new HashSet<>();
        for(Object permission: (List<String>)permissions) {
            permissionsstr.add(String.class.cast(permission));
        }
        loginInfoResp.setPermissions(permissionsstr);*/
        return ResponseEntity.success(loginInfoResp);
    }
}
